<template>

  <!--头: 引入 CommonHead 子组件-->
  <header class="login-by-phone-header">
    <CommonHead title="用户登录"/>
  </header>

  <!--体: 登录表单-->
  <section class="login-by-phone-body">

    <van-divider dashed>使用手机号码登录</van-divider>

    <!--表单: 提交表单时触发-->
    <van-form @submit="loginByPhone">

      <!--单元格: 卡片风格-->
      <van-cell-group inset>
        <!--单元格项: 双绑对应的表单数据，双绑对应的表单校验规则，文字，背景提示字，右侧图标，可清除，不提示-->
        <van-field v-model="formData['phone']" :rules="formRule['phone']"
                   placeholder="请输入手机号码" right-icon="phone-o" clearable autocomplete="off"/>
        <van-field v-model="formData['vcode']" :rules="formRule['vcode']"
                   placeholder="请输入验证码" clearable>
          <template #button>
            <!--按钮: 小号，线条，主要蓝，点击时触发-->
            <van-button size="small" plain type="primary" @click="generateVcode">
              发送验证码
            </van-button>
          </template>
        </van-field>
      </van-cell-group>

      <!--操作区: 登录按钮-->
      <article class="operation">

        <!--提交按钮: 圆角，区块，主要蓝，提交功能-->
        <van-button round block type="primary" native-type="submit">登录</van-button>
        <br/>

        <!--间距-->
        <van-space size="30px">
          <span @click="router.push('/Register')">注册新账号</span>
          <span @click="router.push('/LoginByAccount')">账号密码登录</span>
        </van-space>

      </article>

    </van-form>
  </section>
</template>

<script setup>
import CommonHead from "@/components/CommonHead";
import {GENERATE_VCODE, LOGIN_BY_PHONE} from '@/api/user';
import {reactive, shallowReactive} from "vue";
import {useStore} from 'vuex';
import router from "@/router";
import {showFailToast, showSuccessToast} from "vant";
import {SUCCESS} from "@/constant";

/* ==================== data ==================== */

// data: Vuex实例，直接使用useStore()会报错
let vuex = useStore();

// data: 登录表单数据对象
let formData = shallowReactive({'phone': '', 'vcode': ''});

// data: 登录表单校验规则
let formRule = reactive({
  'phone': [
    {required: true, message: '手机号码不能为空'},
    {pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/, message: '手机号码格式不正确'}
  ],
  'vcode': [
    {required: true, message: '验证码不能为空'},
    {pattern: /^[0-9]{4}$/, message: '验证码格式不正确'}
  ]
})

/* ==================== method ==================== */

// method: 根据手机号码获取验证码
async function generateVcode() {

  // 获取表单中的手机号码
  let phone = formData['phone'];

  // 非空校验手机号码
  if ('' === phone.trim()) {
    showFailToast('手机号码不能为空');
    return false;
  }

  // 异步调用对应API接口
  let result = await GENERATE_VCODE(phone);
  let resp = result['data'];
  if (resp.code === SUCCESS) {
    showSuccessToast('验证码发送成功');
    // 将后台生成的验证码回注到formData中
    formData['vcode'] = resp.data;
  } else {
    showFailToast(resp.message + ': ' + resp.data)
  }
}

// method: 当点击登录按钮时触发
function loginByPhone() {

  // 同步调用按账号密码登录的接口
  LOGIN_BY_PHONE(formData).then(result => {
    let resp = result['data'];
    if (resp.code === SUCCESS) {
      let data = resp.data;

      // 将用户的Token令牌存入sessionStorage中
      sessionStorage.setItem('token', data['token']);

      // 将用户ID存入sessionStorage中
      sessionStorage.setItem('userId', data['user']['userId']);

      // 将用户登录状态存入Vuex中
      vuex.dispatch('setLoginFlag', true);

      // 提示登录成功
      showSuccessToast("登录成功");

      // 跳转到Personal组件
      router.push("/Personal");

    } else {
      showFailToast(resp.message + ': ' + resp.data);
    }
  }).catch(err => console.error(err));
}
</script>

<style scoped lang="scss">
.login-by-phone-body {
  /*操作区*/
  .operation {
    margin: 15px; // 外边距
  }
}
</style>